import {Component, NgZone, ViewChild} from '@angular/core';
import {Content, Events, InfiniteScroll, IonicPage, ModalController, NavController, NavParams} from 'ionic-angular';
import {Util} from "@providers/util";
import {DialogProvider} from "@providers/dialog";
import {PagingConfig, PagingProvider} from "@providers/paging";
import {StorageProvider} from "@providers/storage";
import {HttpProvider} from "@providers/http";
import {ManagerProvider} from "@providers/interface/manager";
import {NativeProvider} from "@providers/natives/native";

/**
 * 批量派工界面
 */

@IonicPage()
@Component({
  selector: 'page-mbatch-dispatch',
  templateUrl: 'manager-order-dispatch.html',
})
export class ManagerOrderDispatchPage {
  @ViewChild(Content) content: Content;
  userInfo: any;
  datas: any[] = [];
  datasConfig: PagingConfig = new PagingConfig();
  isCheckedDatas: any[] = [];
  canScrollToTop: boolean = false;//是否显示返回到顶部按钮
  param = this.navParams.data;
  IS_APP: any;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private pagingService: PagingProvider,
              private storageService: StorageProvider,
              private dialog: DialogProvider,
              private http: HttpProvider,
              private modalCtrl: ModalController,
              private zone: NgZone,
              private events: Events,
              private manager: ManagerProvider,
              private native: NativeProvider) {
    this.userInfo = this.storageService.read('userInfo');
    this.IS_APP=this.native.isCordova;
  }

  ionViewDidLoad() {
    this.refresh();
  }

  ionViewWillEnter() {
    this.userInfo = this.storageService.read("userInfo");
    if (!this.native.isMobile()) {
      this.refresh();
    }
  }

  /**
   * 滑动时触发
   */
  scrollContent() {
    this.zone.run(() => {
      let scrollTop = this.content.getContentDimensions().scrollTop;
      if (scrollTop > 400) {
        this.canScrollToTop = true;
      } else {
        this.canScrollToTop = false;
      }
    })
  }

  /**
   * 抢单点击事件
   */
  grabOrders() {
    this.dialog.showConfirm(() => {
      this.dialog.showLoading();
      let temp = [];
      this.isCheckedDatas.forEach(value => {
        temp.push(value.ID);
      });
      this.manager.managerGrabsorder(temp)
        .then(message => {
          this.dialog.hideLoading();
          this.refresh();
          this.isCheckedDatas = [];
          this.events.publish('ManagerOrderPage');//通知业务页面刷新
        })
        .catch(error => {
          this.dialog.showAlert('抢单派工失败！' + error);
          this.dialog.hideLoading();
        });
    }, '是否执行抢单派工操作？');
  }

  /**
   * 派工
   */
  dispatch() {
    let isRepeat = false;//是否有网点或单据类型不一样的订单
    //如果选中的订单与第一条订单的网点代码不一样，则自动删除
    this.isCheckedDatas.forEach(value => {
      if (value.PROVIDER != this.isCheckedDatas[0].PROVIDER || value.djlx != this.isCheckedDatas[0].djlx) {
        value.isChecked = false;
        isRepeat = true;
      }
    });
    this.isCheckedDatas = this.datas.filter(value => {
      return value.isChecked;
    });
    if (isRepeat) {
      this.dialog.showAlert('您选中了网点或单据类型不一样的订单，已自动帮您去重，请重新确认您选中的单据！');
      return;
    }
    let a = {};
    a['WD'] = this.isCheckedDatas[0].PROVIDER;
    if (this.isCheckedDatas[0].SERVICETYPEID == 1) {
      a['shlx'] = '1';
    } else {
      a['fwlx'] = '1';
    }
    let modal = this.modalCtrl.create('ManagerMworksPage', a);
    modal.onDidDismiss(value => {
      if (value) {
        let temp = {};
        temp['ZCR'] = this.userInfo.RYXX02;
        if (this.isCheckedDatas[0].SERVICETYPEID == 1) {
          temp['XZSHRYDM'] = value.KEY;
          temp['XZSHRY'] = value.VALUE;
        } else {
          temp['FWRYDM'] = value.KEY;
          temp['FWRY'] = value.VALUE;
        }
        temp['LIST'] = [];
        this.isCheckedDatas.forEach(value => {
          temp['LIST'].push({"GD01": value.ID});
        });
        this.dialog.showLoading();
        this.http.post("/Inbound/invoke.do", {
          interfaceId: "csm.css.jcdy.cssorderjk.jx",
          data: JSON.stringify(temp)
        }).subscribe(message => {
          this.dialog.hideLoading();
          this.refresh();
          this.isCheckedDatas = [];
          this.events.publish('ManagerOrderPage ');//通知业务页面刷新
        }, error => {
          this.dialog.showAlert('派工失败！' + error);
          this.dialog.hideLoading();
        });
      }
    });
    modal.present();
  }

  /**
   * item check 点击事件
   */
  checkClick(data: any) {
    data.isChecked = !data.isChecked;
    this.isCheckedDatas = this.datas.filter(value => {
      return value.isChecked;
    })
  }

  /**
   * 全选或全不选点击事件
   */
  checkedAllOrAllno() {
    if (this.isCheckedDatas.length != this.datas.length) {
      this.datas.forEach(value => {
        value.isChecked = true;
      })
    } else {
      this.datas.forEach(value => {
        value.isChecked = false;
      })
    }
    this.isCheckedDatas = this.datas.filter(value => {
      return value.isChecked;
    })

  }

  /**
   * 刷新数据
   */
  refresh(refresher?: any) {
    this.datasConfig = new PagingConfig();
    this.getData(data => {
      this.datas = data;
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    }, this.datasConfig, error2 => {
      if (refresher) {
        setTimeout(() => {
          refresher.complete();
        }, 500);
      }
    });
  }


  //上拉刷新事件
  getMoreDatas(infiniteScroll: InfiniteScroll) {
    this.getData((value) => {
      this.datas.push.apply(this.datas, value);
      infiniteScroll.complete();
    }, this.datasConfig);
  }

  /**
   * 获取数据
   * @param pagingConfig 分页
   * @param fn 方法
   * @param errorFun 方法
   */
  private getData(fn: (value) => void, pagingConfig, errorFun?: (error) => void) {
    this.pagingService.get({
      interfaceId: "csm.som.cssOrderquery.selectSOrder",
      data: {
        "RYXX01": this.userInfo.RYXX01,
        "GDLC": "DPG",
        "searchText": this.param['searchText'],
        "YYSJ": this.param['YYSJ'],
        "DJLY": this.param['DJLY'],
        "DDZT": this.param['DDZT'],
        "DJLX": this.param['DJLX']
      }
    }, pagingConfig).subscribe(data => {
      data.forEach((v) => {
        v.isChecked = false;
        if (v.SERVICETYPEID == 1) {
          v.djlx = 'wl';
        } else {
          v.djlx = 'fw';
        }
        let d: Date = new Date(v.THRUTIME);
        if (!isNaN(v.THRUTIME)) {
          v.THRUTIME = Util.dateFormat(d, "yyyy-MM-dd")
        }
      });
      fn(data);
    }, error => {
      if (errorFun) {
        errorFun(error);
      }
    });
  }

}
